﻿using Digitalmes.Attributes;
using Digitalmes.Services;
using Digitalmes.Signals;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;


namespace Digitalmes.Pipelines
{
    [Order(1)]
    public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
     where TRequest : notnull
    {
        private readonly  ILogService _logger;
        private readonly Stopwatch _timer;
        public LoggingBehavior(ILogService log)
        {
            _logger =log;
            _timer = new Stopwatch();
        }

        public async Task<TResponse> Handle(
            TRequest request,
            RequestHandlerDelegate<TResponse> next,
            CancellationToken cancellationToken)
        {
            _timer.Start();

            var att=typeof(TRequest).GetCustomAttribute<DescriptionAttribute>();

            if (request is SignalBase signalBase)
            {
                var str = new StringBuilder();

                str.Append($"开始处理:{request.GetType().Name} {signalBase.Sn} {signalBase.ProductCode}");

                _logger.Information(str.ToString());
            }
            else
            {
                _logger.Information($"开始处理:{request.GetType().Name}");
            }

            try
            {
                var response = await next();
                _timer.Stop();

                _logger.Information($"结束处理:{request.GetType().Name} {_timer.Elapsed.TotalMilliseconds}ms");

                return response;
            }
            catch (Exception ex)
            {
                if (att != null)
                {
                    _logger.Error(  $"{att.Description}请求出错:-{request}",ex);
                }
                else
                {
                    _logger.Error( $"请求出错:{typeof(TRequest).Name}-{request}",ex);
                }
                  return default(TResponse);
            }
        }
    }
}
